<template>
  <inject-template :item="item" :pageId="pageId" :popId="popId">
    <template v-slot:common>
      <canvas v-if="!isSVG" :id="'c-' + item.id" class="wb-moveable" :width="getCanvasWidth" :height="getCanvasHeight"></canvas>
    </template>
  </inject-template>
</template>

<script>
import InjectTemplate from '@/components/inject-template.vue'
import { utils } from '@/components/utils/utils'
import { commonUtils } from '@/components/utils/common-utils'
import { EventBus } from '@/store/index'
import { MOBILE_WID_HEI } from '@/common/const-dif'
import { ref } from 'vue'

const DELETE_OFFSET = 28
const DELETE_SIZE = 48

export default {
  name: "WbMoveable",
  mixins: [utils, commonUtils],
  setup () {
    const state =  {
      dragLists: [],
      canvas: null,
      fabric: null,
      canvasCon: null,
      img: null,
      isSVG: ref(false)
    }
    return state
  },
  components: {
    InjectTemplate,
  },
  created() {
    if(!this.isH5Edit) {
      EventBus.$off("addImgToCanvas", this.onAddDragItem);
      EventBus.$on("addImgToCanvas", this.onAddDragItem);
      EventBus.$off("addImgToCanvasBg", this.onAddCanvasBackground);
      EventBus.$on("addImgToCanvasBg", this.onAddCanvasBackground);
      EventBus.$off("exportSVG", this.onExportSVG);
      EventBus.$on("exportSVG", this.onExportSVG);
    }
  },
  computed: {
    getCanvasWidth() {
      return this.item.conAttr.width/MOBILE_WID_HEI.adaptiveScale
    },
    getCanvasHeight() {
      return this.item.conAttr.height/MOBILE_WID_HEI.adaptiveScale
    }
  },
  mounted() {
    if(window.fabric) {
      this.initFabric(window.fabric);
    }
  },
  methods: {
    initFabric(fabric) {
      this.fabric = fabric;
      this.canvas = this.__canvas = new fabric.Canvas('c-' + this.item.id);
      // create a rect object
      let deleteIcon = "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg version='1.1' id='Ebene_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='595.275px' height='595.275px' viewBox='200 215 230 470' xml:space='preserve'%3E%3Ccircle style='fill:%23F44336;' cx='299.76' cy='439.067' r='218.516'/%3E%3Cg%3E%3Crect x='267.162' y='307.978' transform='matrix(0.7071 -0.7071 0.7071 0.7071 -222.6202 340.6915)' style='fill:white;' width='65.545' height='262.18'/%3E%3Crect x='266.988' y='308.153' transform='matrix(0.7071 0.7071 -0.7071 0.7071 398.3889 -83.3116)' style='fill:white;' width='65.544' height='262.179'/%3E%3C/g%3E%3C/svg%3E";
      // let cloneIcon = "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='iso-8859-1'%3F%3E%3Csvg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 55.699 55.699' width='100px' height='100px' xml:space='preserve'%3E%3Cpath style='fill:%23010002;' d='M51.51,18.001c-0.006-0.085-0.022-0.167-0.05-0.248c-0.012-0.034-0.02-0.067-0.035-0.1 c-0.049-0.106-0.109-0.206-0.194-0.291v-0.001l0,0c0,0-0.001-0.001-0.001-0.002L34.161,0.293c-0.086-0.087-0.188-0.148-0.295-0.197 c-0.027-0.013-0.057-0.02-0.086-0.03c-0.086-0.029-0.174-0.048-0.265-0.053C33.494,0.011,33.475,0,33.453,0H22.177 c-3.678,0-6.669,2.992-6.669,6.67v1.674h-4.663c-3.678,0-6.67,2.992-6.67,6.67V49.03c0,3.678,2.992,6.669,6.67,6.669h22.677 c3.677,0,6.669-2.991,6.669-6.669v-1.675h4.664c3.678,0,6.669-2.991,6.669-6.669V18.069C51.524,18.045,51.512,18.025,51.51,18.001z M34.454,3.414l13.655,13.655h-8.985c-2.575,0-4.67-2.095-4.67-4.67V3.414z M38.191,49.029c0,2.574-2.095,4.669-4.669,4.669H10.845 c-2.575,0-4.67-2.095-4.67-4.669V15.014c0-2.575,2.095-4.67,4.67-4.67h5.663h4.614v10.399c0,3.678,2.991,6.669,6.668,6.669h10.4 v18.942L38.191,49.029L38.191,49.029z M36.777,25.412h-8.986c-2.574,0-4.668-2.094-4.668-4.669v-8.985L36.777,25.412z M44.855,45.355h-4.664V26.412c0-0.023-0.012-0.044-0.014-0.067c-0.006-0.085-0.021-0.167-0.049-0.249 c-0.012-0.033-0.021-0.066-0.036-0.1c-0.048-0.105-0.109-0.205-0.194-0.29l0,0l0,0c0-0.001-0.001-0.002-0.001-0.002L22.829,8.637 c-0.087-0.086-0.188-0.147-0.295-0.196c-0.029-0.013-0.058-0.021-0.088-0.031c-0.086-0.03-0.172-0.048-0.263-0.053 c-0.021-0.002-0.04-0.013-0.062-0.013h-4.614V6.67c0-2.575,2.095-4.67,4.669-4.67h10.277v10.4c0,3.678,2.992,6.67,6.67,6.67h10.399 v21.616C49.524,43.26,47.429,45.355,44.855,45.355z'/%3E%3C/svg%3E%0A"
      let deleteImg = document.createElement('img');
      deleteImg.src = deleteIcon;
      // let cloneImg = document.createElement('img');
      // cloneImg.src = cloneIcon;

      fabric.Object.prototype.set({
      borderColor: this.commonAttr.borderColor ? this.commonAttr.borderColor : '#127BFF',
      cornerColor: this.commonAttr.cornerColor ? this.commonAttr.cornerColor : '#127BFF', //激活状态角落图标的填充颜色
      cornerStrokeColor: 'white', //激活状态角落图标的边框颜色
      // borderOpacityWhenMoving: 1,
      // borderScaleFactor: 1,
      cornerSize: 32/MOBILE_WID_HEI.adaptiveScale,
      cornerStyle: "circle", //rect,circle
      // centeredScaling: false, //角落放大缩小是否是以图形中心为放大原点
      // centeredRotation: true, //旋转按钮旋转是否是左上角为圆心旋转
      transparentCorners: false, //激活状态角落的图标是否透明
      // rotatingPointOffset: 80/MOBILE_WID_HEI.adaptiveScale, //旋转距旋转体的距离
      // originX: "center",
      // originY: "center",
      // lockUniScaling: false, //只显示四角的操作
      // hasRotatingPoint: true, //是否显示旋转按钮
      // selectionDashArray: [5, 5],
      // borderDashArray: [16, 16],
      // strokeWidth: 4,
      // controls: { mtr: { offsetY: 48 } },
      padding: 24/MOBILE_WID_HEI.adaptiveScale,
    });
    
      fabric.Object.prototype.controls.deleteControl = new fabric.Control({
        x: 0.5,
        y: -0.5,
        offsetY: -DELETE_OFFSET/MOBILE_WID_HEI.adaptiveScale,
        offsetX: DELETE_OFFSET/MOBILE_WID_HEI.adaptiveScale,
        cursorStyle: 'pointer',
        mouseUpHandler: this.deleteDragItem,
        render: this.renderIcon(deleteImg),
        cornerSize: DELETE_SIZE/MOBILE_WID_HEI.adaptiveScale
      });
    
      // fabric.Object.prototype.controls.clone = new fabric.Control({
      //   x: -0.5,
      //   y: -0.5,
      //   offsetY: -16,
      //   offsetX: -16,
      //   cursorStyle: 'pointer',
      //   mouseUpHandler: this.cloneDragItem,
      //   render: this.renderIcon(cloneImg),
      //   cornerSize: 24
      // });
    },
    onAddDragItem(item) {
      let fabric = this.fabric;
      let canvas = this.canvas;
      let this_ = this;
      let dragLists = this.dragLists;
      let clientWidth = this.item.conAttr.width/MOBILE_WID_HEI.adaptiveScale;
      let clientHeight = this.item.conAttr.height/MOBILE_WID_HEI.adaptiveScale; 
      let itemLeft = (clientWidth - item.width) / 2;
      let itemTop = (clientHeight - item.height) / 2;

      let oImg = new fabric.Image();
      oImg.setSrc(item.url, function(oImg) {
        oImg.scale(item.width/oImg.width).set({
          left: itemLeft,
          top: itemTop,
        });
        canvas.add(oImg).setActiveObject(oImg);
        canvas.item(0).controls.mtr.offsetY = -parseFloat(40);
        canvas.requestRenderAll();

        oImg.id = dragLists.length;
        dragLists.push(oImg);
        this_.cameraDisplayMoveable();
      }, { crossOrigin: "anonymous" });
    },
    onAddCanvasBackground(item) {
      let fabric = this.fabric;
      let canvas = this.canvas;
      fabric.Image.fromURL(item.url, function(oImg) {
        oImg.scale(1/MOBILE_WID_HEI.adaptiveScale).set({
          left: 0,
          top: 0,
        });
        canvas.setBackgroundImage(oImg, canvas.renderAll.bind(canvas));
      }, { crossOrigin: "anonymous" });
    },
    renderIcon(icon) {
      let fabric = this.fabric;
      return function renderIcon(ctx, left, top, styleOverride, fabricObject) {
        let size = this.cornerSize;
        ctx.save();
        ctx.translate(left, top);
        ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle));
        ctx.drawImage(icon, -size/2, -size/2, size, size);
        ctx.restore();
      }
    },
    deleteDragItem(eventData, transform) {
      let target = transform.target;
      let canvas = target.canvas;
      canvas.remove(target);
      canvas.requestRenderAll();

      this.dragLists = _.cloneDeep(_.pullAllBy(this.dragLists, [{ id: target.id }], 'id'));
      this.cameraDisplayMoveable();
    },
    cloneDragItem(eventData, transform) {
      let target = transform.target;
      let canvas = target.canvas;
      target.clone(function(cloned) {
        cloned.left += 10;
        cloned.top += 10;
        canvas.add(cloned);
      });
    },
    onExportSVG() {
      // this.canvas.setActiveObject();
      this.canvasCon = document.getElementsByClassName("canvas-container")[0];
      // let doc = new DOMParser().parseFromString(this.canvas.toSVG(), "text/xml");
      // let svg = this.svg = doc.getElementsByTagName("svg")[0];
      // svg.style.position = "absolute";
      // svg.style.left = "0";
      // svg.style.top = "0";
      // svg.style.width = "100%";
      // svg.style.height = "100%";
      // this.canvasCon.appendChild(svg);
      // this.isSVG = true;

      // var svg = canvas.toSVG({
      //   viewBox: {
      //     x: 100,
      //     y: 100,
      //     width: 200,
      //     height: 300
      //   }
      // });
      let dataURL = this.canvas.toDataURL({
        format: 'png',
        // quality: 0.8,
        multiplier: 2,
        // left: 100,
        // top: 100,
        // width: 200,
        // height: 200
      });
      let oImgBox = document.createElement("img");
      oImgBox.crossOrigin = "Anonymous";
      oImgBox.src = dataURL;
      oImgBox.style.position = "absolute";
      oImgBox.style.left = "0";
      oImgBox.style.top = "0";
      oImgBox.style.width = "100%";
      oImgBox.style.height = "100%";
      this.canvasCon.appendChild(oImgBox);
      this.img = oImgBox;

      this.isSVG = true;
    },
    clearDragIcon() {
      // let dragItems = this.canvas.getActiveObjects();
      while(this.dragLists.length > 0) {
        let dragItem = this.dragLists.pop();
        this.canvas.remove(dragItem);
      }  
    },
    cameraDisplayMoveable(){
      if(this.dragLists.length > 0){
        EventBus.$emit("cameraDisplayMoveable", { isDisplay: true });
      }else{
        EventBus.$emit("cameraDisplayMoveable", { isDisplay: false });
      }
    }
  },
  beforeUnmount(){
    EventBus.$off("addImgToCanvas", this.onAddDragItem);
    EventBus.$off("addImgToCanvasBg", this.onAddCanvasBackground);
    EventBus.$off("exportSVG", this.onExportSVG);
    if(this.fabric){
      this.clearDragIcon();
      this.canvas.removeListeners();
      this.canvas.clear();
    }
    this.canvas = null;
    this.fabric = null;
    if(this.img) {
      this.canvasCon.removeChild(this.img);
    }
    this.canvasCon = null;
    this.img = null;
  },
};
</script>

<style lang="scss">
.wb-moveable {
  width: inherit;
  height: inherit;
  position: relative;
}
</style>
